const express = require("express");
let router = express.Router();
const fs = require("fs");
const newsModel = require("../modules/newsModel.js")
router.get("/shownews", async (req, res) => {
    // res.send("显示新闻列表页面");
    let copydata = await newsModel.find();
    // 计算 总的页码是多少 ？
    // 获取数据的总条数 ；
    let totalCount = copydata.length;
    // 每页显示的数量  perpage
    let perpage = 5;
    if (typeof req.query.perpage !== "undefined") {
        perpage = req.query.perpage;
    }
    let page = Math.ceil(totalCount / perpage);
    // 根据当前的页码 显示对应的数据；
    let p = 1;//页码默认值
    if (typeof req.query.p !== "undefined") {
        p = req.query.p;
    }
    let resdata = await newsModel.find().skip((p - 1) * 5).limit(perpage);
    console.log(resdata);
    // res.send("显示新闻列表页面");
    res.render("index.ejs", { resdata, page })
})
router.get("/detail", async (req, res) => {
    let { id } = req.query;
    console.log(id);
    let newsdata = await newsModel.find({ _id: id });
    console.log("newsdata",newsdata);
    let data = newsdata[0]
    res.render("detail.ejs",  data );
})

module.exports = router;